﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MipsPipelineSimulator
{
    class MasterSwitch
    {
        static private Thread mainThread = null;

        static private MainForm mainForm = null;

        static private void ThreadFun()
        {
            //初始化
            Initialize();
            //判断是否要继续
            while (true)
            {
                if (!IFRun())
                {
                    break;
                }
                else
                {
                    IFStage.Start(mainForm);
                    IDStage.Start(mainForm);
                    EXStage.Start(mainForm);
                    MEMStage.Start(mainForm);
                    WBStage.Start(mainForm);

                    // 等待所有的线程结束
                    IFStage.Wait();
                    IDStage.Wait();
                    EXStage.Wait();
                    MEMStage.Wait();
                    WBStage.Wait();
                }
            }
        }

        static public void Start(MainForm param)
        {
            mainForm = param;
            mainThread = new Thread(new ThreadStart(ThreadFun));
            mainThread.Start();
        }

        static private void Initialize()
        {
            //设置开始能否运行
            IFStage.enableRun = 0;
            IDStage.enableRun = -1;
            EXStage.enableRun = -1;
            MEMStage.enableRun = -1;
            WBStage.enableRun = -1;
        }

        static private bool IFRun()
        {
            return (IFStage.enableRun >= 0 || IDStage.enableRun >= 0 || EXStage.enableRun >= 0 || MEMStage.enableRun >= 0 || WBStage.enableRun >= 0);
        }

        static public void Close()
        {
            if (mainThread != null && mainThread.IsAlive)
            {
                mainThread.Abort();
            }
            IFStage.Close();
        }
    }
}
